package ext.tianma.soap.conf;

import java.io.File;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import ext.tianma.soap.SOAPService;
import wt.util.WTProperties;

public class SOAPConfig {
	public static final String SendProject = "SendProject";
	
	public static String ServerHost;
	public static String ServerPort;
	public static String UserName;
	public static String Password;
	
	private Document confDoc = null;
	
	public SOAPConfig(){
		SAXReader reader = new SAXReader();
		WTProperties props;
		try {
			URL s = SOAPConfig.class.getResource("SOAPConfig.xml");
			confDoc = reader.read(s.getFile());
			init();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public SOAPConfig(File confFile){
		SAXReader reader = new SAXReader();
		try {
			confDoc = reader.read( confFile );
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void init(){
		Element root = confDoc.getRootElement();
		ServerHost = root.attributeValue("ServerHost");
		ServerPort = root.attributeValue("ServerPort");
		UserName = root.attributeValue("UserName");
		Password = root.attributeValue("Password");
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SOAPConfig conf = new SOAPConfig();
		SOAPConfigItem item = conf.getConfigItem(SOAPConfig.SendProject);
		System.out.println(item);
	}
	
	public SOAPConfigItem getConfigItem(String key){
		SOAPConfigItem config = new SOAPConfigItem();
		Element root = confDoc.getRootElement();
		Element e =(Element) root.selectSingleNode( key+"/endpoint" );
		if(e!=null){
			String endpint = e.getText();
			if(!"true".equalsIgnoreCase(e.attributeValue("isFullUrl"))){
				if(endpint.startsWith("/")){
					endpint = "http://" + ServerHost + ":" + ServerPort + e.getText();
				}else{
					endpint = "http://" + ServerHost + ":" + ServerPort + "/" + e.getText();
				}
			}
			config.setEndpoint( endpint );
		}
		e =(Element) root.selectSingleNode( key+"/xslt" );
		if(e!=null){
			String xslt;
			xslt = e.getText();
			if(!"true".equalsIgnoreCase(e.attributeValue("isFullPath"))){
				URL s = SOAPConfig.class.getResource(xslt);
				xslt = s.getFile();
			}
			config.setXslt( xslt );
		}
		
		e =(Element) root.selectSingleNode( key+"/SOAPAction" );
		if(e!=null){
			String action;
			action = e.getText();
			config.setSoapAction(action );
		}
		
		return config;
	}
	

}
